package kos.robert.loader;

import java.awt.*;

import javax.swing.ImageIcon;
import kos.robert.animation.Animation;
import kos.robert.screens.ScreenManager;

public class BufferedAnimationLoader {

	public static void main(String[] args) {
		BufferedAnimationLoader animationLoader = new BufferedAnimationLoader();
		animationLoader.run();
	}

	private ScreenManager screen;
	private Image bg;
	private Animation animation;

	private static final DisplayMode modes1[] = { new DisplayMode(1024, 768, 32, 60),
			new DisplayMode(1024, 768, 24, 0), new DisplayMode(1024, 768, 16, 0), new DisplayMode(800, 600, 32, 0),
			new DisplayMode(800, 600, 24, 0), new DisplayMode(800, 600, 16, 0), new DisplayMode(640, 480, 32, 0),
			new DisplayMode(640, 480, 24, 0), new DisplayMode(640, 480, 16, 0), };

	// main method called from main
	public void run() {
		screen = new ScreenManager();
		try {
			DisplayMode dm = screen.findFirsCompatibleDisplaymode(modes1);
			screen.setFullScreen(null); // to set native resolution
			loadImages();
			movieLoop();
		} finally {
			screen.restoreScreen();
		}
	}

	// load images and add scenes
	public void loadImages() {
		bg = new ImageIcon("resources/graphics/back.png").getImage();
		Image face1 = new ImageIcon("resources/graphics/face.png").getImage();
		Image face2 = new ImageIcon("resources/graphics/face01.png").getImage();
		animation = new Animation(true);
		animation.addScene(face1, 250);
		animation.addScene(face2, 250);
	}

	public void movieLoop() {
		long startingTime = System.currentTimeMillis();
		long cumTime = startingTime;

		while (cumTime - startingTime < 5000) {
			long timePassed = System.currentTimeMillis() - cumTime;
			cumTime += timePassed;
			animation.update(timePassed);

			Graphics2D g = screen.getGraphics();			
			draw(g);
			g.dispose();
			screen.update();

			try {
				 Thread.sleep(15);
			} catch (Exception e) {
			}
		}
	}

	// draw graphics
	public void draw(Graphics g) {
		g.clearRect(0, 0, screen.getWidth(), screen.getHeight());
		g.drawImage(bg, 0, 0, null);
		g.drawImage(animation.getImage(), 0, 0, null);
	}
}